package br.edu.fcsl.web.servelets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.edu.fcsl.entidade.Usuario;
import br.edu.fcsl.persistencia.UsuarioDAO;

/**
 * Servlet implementation class ServLogin
 */
@WebServlet("/ServLogin")
public class ServLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
			
			String login = request.getParameter("login");
			String senha = request.getParameter("senha");
			
			UsuarioDAO usuario = new UsuarioDAO();
			
			List<Usuario> user = usuario.listarUsuario();
			HttpSession session = request.getSession();
			
			int validar = 0;
			int validar2 = 0;
			Long id = null;
			
			for (Usuario usuario2 : user) {
				
				if(usuario2.getUsuario().equals(login)){
				
				validar = 1;
				id = Long.valueOf(usuario2.getId());
				session.setAttribute("valLogin", login);
				
				}
				if(usuario2.getSenha().equals(senha)){
					
					validar2 = 1;
					id = Long.valueOf(usuario2.getId());
					
					}
			}
			
		
			
			
			
			if(login == "" || senha == "" || validar == 0 || validar2 == 0){
			
				
				session.setAttribute("login", "setar");				
				session.setAttribute("senha", "setar");
				
				
					if(login ==""){  
						
						session.setAttribute("login", "erro");
											
					}if(validar == 0 && login != ""){
						
						session.setAttribute("login", "erro2");
					}
					
					if(senha ==""){ 
						
						session.setAttribute("senha", "erro");
					}if(validar2 == 0 && login != ""){
						
						session.setAttribute("senha", "erro2");
					}
				
				
				
				
				response.sendRedirect("index.jsp");
				
				
			}else{			

				
				session.setAttribute("usuario_autenticado", login);
				session.setAttribute("id_usuario_autenticado", id);
				session.setAttribute("confirma", "0");

	                 response.sendRedirect("admin/listaProdutos.jsp");

	            }
			
			
		
		
	

	}}
